package com.lxyk.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.lxyk.yygh.common.exception.YyghException;
import com.lxyk.yygh.common.result.ResultCodeEnum;
import com.lxyk.yygh.enums.PaymentTypeEnum;
import com.lxyk.yygh.enums.RefundStatusEnum;
import com.lxyk.yygh.model.order.OrderInfo;
import com.lxyk.yygh.model.order.PaymentInfo;
import com.lxyk.yygh.model.order.RefundInfo;
import com.lxyk.yygh.order.service.OrderService;
import com.lxyk.yygh.order.service.RefundInfoService;
import com.lxyk.yygh.order.service.WeixinService;
import com.lxyk.yygh.order.utils.ConstantPropertiesUtils;
import com.lxyk.yygh.order.utils.ExpireUtils;
import com.lxyk.yygh.order.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinServiceImpl  implements WeixinService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentServiceImpl paymentService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RefundInfoService refundInfoService;

    /**
     * 根据订单号下单，生成支付链接
     */

    @Override
    public Map createNative(Long orderId) {


    try {
        //从redis获取数据
        Map payMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
        if (payMap != null) {
            return payMap;
        }
        //1.根据订单Id获取订单信息
        OrderInfo orderInfo = orderService.getById(orderId);
        //2.向支付记录表中添加信息，保存交易记录
        //ALIPAY(1,"支付宝"),
        //WEIXIN(2,"微信" );
        paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());
        //设置参数，调用微信生成二维码接口，返回code_url
        //把参数转换成xml格式，使用商户key进行加密
        Map paramMap = new HashMap();
        //请求参数
        //appid 商户号
        paramMap.put("appid", ConstantPropertiesUtils.APPID);
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
        //生成一个唯一的字符串，微信工具类生成
        //WXPayUtil是wxpay的jar里的
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        String body = orderInfo.getReserveDate() + "就诊" + orderInfo.getDepname();
        paramMap.put("body", body);
        //订单编号
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
        //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
        // 金额 为了测试方便  统一写 0.01元
        paramMap.put("total_fee", "1");
        //当前ip地址本地
        paramMap.put("spbill_create_ip", "127.0.0.1");
        //回调地址
        paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
        //支付类型
        paramMap.put("trade_type", "NATIVE");
        //****设置订单过期时间,2min过期吧先测试一下，后续改10min
        String orderExpireTime = ExpireUtils.getOrderExpireTime(10 * 60 * 1000L);
        paramMap.put("time_expire",orderExpireTime);

        //4、调用微信生成二维码接口  HTTPClient来根据URL访问第三方接口并且传递参数
        //详见微信支付，这是固定地址，请求微信的地址
        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        //client设置参数
        //xml方式设置
//        商户key,抛异常
        httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
        //支持请求
        httpClient.setHttps(true);
        //调用post方法进行发送
        httpClient.post();
        //5、返回相关的数据，微信那边返回的内容
        String xml = httpClient.getContent();
        System.out.println("------------微信返回------------");
        System.out.println("xml"+xml);
        System.out.println("------------微信返回------------");

        //xml拿到前端不方便，把xml转成map集合，在传到前端页面更方便
        Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
        System.out.println("resultMap = " + resultMap);
        //6、封装返回结果集
        Map map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("totalFee", orderInfo.getAmount());
        map.put("resultCode", resultMap.get("result_code"));

        //二维码地址
        map.put("codeUrl", resultMap.get("code_url"));
        //业务结果	result_code
        if(null != resultMap.get("result_code")){
            //微信支付设置设置了2min,改
            redisTemplate.opsForValue().set(orderId.toString(),map,2, TimeUnit.MINUTES);
        }

        return map;

    }catch (Exception e) {
        e.printStackTrace();

         }
        return null;
    }

    //调用微信接口实现支付状态查询
    @Override
    public Map<String, String> queryPayStatus(Long orderId) {

        try {
            //根据orderId进行查询
            OrderInfo orderInfo = orderService.getById(orderId);
            if (orderInfo == null) {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }

            String outTradeNo = orderInfo.getOutTradeNo();//订单号
            //2.封装参数进行请求
            Map<String, String> param = new HashMap<>();
            param.put("appid", ConstantPropertiesUtils.APPID);
            param.put("mch_id", ConstantPropertiesUtils.PARTNER);
            param.put("out_trade_no", orderInfo.getOutTradeNo());
            //wx 第三包提供
            param.put("nonce_str", WXPayUtil.generateNonceStr());
            //设置签名，必须

            ////3、设置请求内容
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            //httpClient.setXmlParam(WXPayUtil.mapToXml(param)); 错误
            //必须设置sign
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(param, ConstantPropertiesUtils.PARTNERKEY));
            httpClient.setHttps(true);
            httpClient.post();
            //4、得到微信接口返回的数据，转成Map
            String xml = httpClient.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("调用微信接口实现支付状态查询"+resultMap);
            //4、返把接口数据返回
            return resultMap;
        }catch (Exception e){
            e.printStackTrace();
        }
                return null;
    }

//    退款
    @Override
    public Boolean refund(Long orderId) {
        try {
            //根据orderId查询订单
            //获取支付记录信息
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            //添加信息到退款记录表
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
            //获取退款状态
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                //已经退款
                return true;
            }
            //没有退款
            //调用微信接口实现退款
            //封装需要参数

            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);       //公众账号ID
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());   //字符串
            paramMap.put("transaction_id", paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no", paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no", "tk" + paymentInfo.getOutTradeNo()); //商户退款单号
            paramMap.put("total_fee", "1");  //一分钱
            paramMap.put("refund_fee", "1"); //一分钱
            String paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);

            //设置调用接口内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            //设置证书信息
            //去修改配置文件类（ConstantPropertiesUtils），添加证书路径，没有获取路径无法退款成功
            // TODO: 完善HttpClient类获取证书路径 excute()方法
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();

            //接收返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            // 根据result_code状态码进行判断，如果状态码是（SUCCESS），就表示当前退款成功
            // 如果退款成功，就更新退款记录表，把里面的状态改为（已退款）
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
}
